package com.wbpay.sdk.pay.wechat;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;

import com.wbpay.sdk.constant.Constants;
import com.wbpay.sdk.framework.IPayFunction;
import com.wbpay.sdk.framework.PayResult;
import com.wbpay.sdk.params.PayParams;
import com.wbpay.sdk.pay.IPay;
import com.wbpay.sdk.utils.Log;
import com.wbpay.sdk.utils.Utils;

import java.util.HashMap;
import java.util.Map;

/**
 * 微信支付模块
 */
public class WechatPay implements IPay {

    private Context mContext;
    private IPayFunction mPayFunction;

    @Override
    public void init(Context context, IPayFunction f) {
        mContext = context;
        mPayFunction = f;
    }

    @Override
    public void pay(PayParams payParams) {
        payByWxDirect(payParams);
    }

    private void payByWxDirect(PayParams payParams) {
        if (payParams == null) {
            String desc = mContext.getString(Utils.getStringId(mContext, "jy_null_payparams"));
            mPayFunction.notifyPayResult(PayResult.PAY_FAILURE, desc, this);
            return;
        }
        String broadcastAction = setupAndGetBroadcast();
        WxPayHelper.setCallback(broadcastAction);
        WxPayHelper.setPackage(mContext.getPackageName());
        Map<String, String> params = new HashMap<String, String>();
        params.put("appid", WxPayConfig.APP_ID);

        params.put("mch_id", WxPayConfig.PARTNER_ID);

        params.put("nonce_str", WxPayHelper.getRandom32());

        /**
         * 商品描述交易字段格式根据不同的应用场景按照以下格式：
         * APP——需传入应用市场上的APP名字-实际商品名称，天天爱消除-游戏充值。
         */
        params.put("body", payParams.getSubject());

        /**
         * 透传参数
         */
        params.put("attach", payParams.getAttach());

        params.put("out_trade_no", payParams.getOrder()); // 商户订单号

        params.put("total_fee", String.valueOf(payParams.getPrice()));

        params.put("spbill_create_ip", WxPayHelper.getLocalIpAddress());

        params.put("notify_url", WxPayConfig.NOTIFY_URL);

        params.put("trade_type", "APP");

        WxPayHelper.wxgfPay(mContext, params);
    }

    @Override
    public String getPayName() {
        return mContext.getString(Utils.getStringId(mContext, "jy_pay_list_activity_wx_pay"));
    }

    @Override
    public int getPayType() {
        return PAY_TYPE_WECHATPAY;
    }

    @Override
    public boolean checkPayAvailable() {
        if (!Utils.isInstalled(mContext, Constants.WX_PKGNAME)) {
            Log.e(Log.TAG, "微信未安装");
            return false;
        }
        return true;
    }

    @Override
    public int getPayIcon() {
        return Utils.getDrawableId(mContext, "jy_wx");
    }

    @Override
    public String getPayDesc() {
        return mContext.getString(Utils.getStringId(mContext, "jy_wxpay_desc"));
    }

    @Override
    public String toString() {
        return getPayName();
    }

    /**
     * 设置微信支付回调广播
     *
     * @return
     */
    private String setupAndGetBroadcast() {
        try {
            // 注销之前注册的广播
            mContext.unregisterReceiver(mBroadcastReceiver);
        } catch (Exception e) {
        }
        String action = mContext.getPackageName() + ".intent.action.WXPAYRESULT";
        IntentFilter filter = new IntentFilter(action);
        String permission = mContext.getPackageName() + ".permission.WX_SEND_RESULT";
        mContext.registerReceiver(mBroadcastReceiver, filter, permission, null);
        return action;
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            mContext.unregisterReceiver(mBroadcastReceiver);
            int error = -1;
            String desc = null;
            if (intent != null) {
                error = intent.getIntExtra("RESULT_CODE", -1);
                desc = intent.getStringExtra("RESULT_DESC");
            }
            Log.d(Log.TAG, "error : " + error + " , desc : " + desc);
            processWxPayResult(error, desc);
        }
    };

    private void processWxPayResult(int error, String desc) {
        int payResult = PayResult.PAY_FAILURE;
        if (error == 0) {
            payResult = PayResult.PAY_SUCCESS;
        } else if (error == -1) {
            payResult = PayResult.PAY_FAILURE;
        } else if (error == -2) {
            payResult = PayResult.PAY_CANCEL;
        }
        if (mPayFunction != null) {
            mPayFunction.notifyPayResult(payResult, desc, this);
        }
    }
}
